//
//  CommonPrefs.m
//  UpFlash
//
//  Created by James Williams on 28/11/2010.
//  Copyright 2010 Kilvo. All rights reserved.
//

#import "CommonPrefs.h"

@implementation CommonPrefs

-(id) init {
	self = [super init];
	if (self) {	
		//NSDictionary *defaults = [NSDictionary dictionaryWithObjectsAndKeys:false, UseBetaKeyString, DefaultFrequencyString, FrequencyKeyString, nil];
		//		[[NSUserDefaults standardUserDefaults] registerDefaults:defaults];
		appID = CFSTR("com.kilvo.upflashmac");
	}
	
	return self;
}

-(NSString*) getFrequency {
	//return [[NSUserDefaults standardUserDefaults] stringForKey:FrequencyKeyString];
	
	CFPropertyListRef value;
	
	value = CFPreferencesCopyAppValue(CFSTR(FrequencyKeyString), appID);
	
	//NSLog(value);
	
	NSString* actualValue = NULL;
	
	if (value && CFGetTypeID(value) == CFStringGetTypeID()) {
		
		//NSLog(@"value: %s", value);
		
//		actualValue = [NSString stringWithUTF8String:value];
//		actualValue = [NSString stringWithCString:value];
//		
//		NSLog(@"actualValue: %s", actualValue);
		
		return value;
	
	}
	else {
		return [NSString stringWithUTF8String:DefaultFrequencyString];
	}
	
	
	//if (value) {
//		CFRelease(value);
//	}
//	
//	
//	if (actualValue) {
//		return actualValue;
//	}
//	else {
//		return [NSString stringWithUTF8String:DefaultFrequencyString];
//	}
}

-(void) setFrequency : (NSString*) newFrequency {
	//	[[NSUserDefaults standardUserDefaults] setObject:newFrequency forKey:FrequencyKeyString];
	
	CFNotificationCenterRef center;
	
    CFPreferencesSetAppValue( CFSTR(FrequencyKeyString), newFrequency, appID );
    CFPreferencesAppSynchronize( appID );
	
    center = CFNotificationCenterGetDistributedCenter();
    CFNotificationCenterPostNotification(center, CFSTR("Preferences Changed"), appID, NULL, TRUE);
}

-(BOOL) getUseBeta {
	//return [[NSUserDefaults standardUserDefaults] boolForKey:UseBetaKeyString];
	
	CFPropertyListRef value;
	
	value = CFPreferencesCopyAppValue(CFSTR(UseBetaKeyString), appID);
	
	BOOL actualValue = NO;
	
	if (value && CFGetTypeID(value) == CFBooleanGetTypeID()) {
		actualValue = CFBooleanGetValue(value);
	}
	
	if (value) {
		CFRelease(value);
	}
	
//	NSLog(@"useBeta read: %b",actualValue);
	
	return actualValue;
}

-(void) setUseBeta : (BOOL) newValue {
	//[[NSUserDefaults standardUserDefaults] setBool:newValue forKey:UseBetaKeyString];
	//NSLog(@"setUseBeta called...");	
	if (newValue) {
	//	NSLog(@"setUseBeta newValue true...");	
		CFPreferencesSetAppValue(CFSTR(UseBetaKeyString), kCFBooleanTrue, appID);
	}
	else {
	//	NSLog(@"setUseBeta newValue false...");	
		CFPreferencesSetAppValue(CFSTR(UseBetaKeyString), kCFBooleanFalse, appID);
	}
	
	CFPreferencesAppSynchronize( appID );
}

@end
